package com.eastfair.projectcore.controller;

import com.eastfair.cache.redis.RedisOps;
import com.eastfair.core.base.R;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * <p>
 * 图形验证码
 * </p>
 *
 * @author ligang
 * @date 2021-07-22
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/kaptcha")
@Api(value = "kaptcha", tags = "图形验证码")
public class KaptchaController {

    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    private RedisOps redisOps;


    /**
     * 2、生成验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/imgKaptcha")
    public void defaultKaptcha(String verifyId, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            String createText = "" + (int) Math.round((Math.random() + 1) * 1000);
            //两分钟过期
            redisOps.setEx(verifyId, createText, 120);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 3、校对验证码
     *
     * @param verifyId
     * @param verifyValue
     * @return
     */
    @GetMapping("/imgvrify")
    public R<Boolean> imgvrify(String verifyId, String verifyValue) {
        String value = redisOps.get(verifyId);
        if (StringUtils.isNotBlank(value) && verifyValue.equals(value)) {
            return R.success(true);
        }
        return R.success(false);
    }


}
